package org.taobao.ibatiside.core.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.xml.stream.XMLResolver;
import javax.xml.stream.XMLStreamException;

import org.apache.commons.lang.ArrayUtils;
import org.eclipse.core.runtime.Platform;
import org.taobao.ibatiside.core.IbatisConstant;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class BatisEntityResolver implements EntityResolver, XMLResolver {

	@Override
	public InputSource resolveEntity(String publicId, String systemId)
			throws SAXException, IOException {
		InputStream is = null;
		try {
			is = (InputStream) resolveEntity(publicId, systemId,null,null);
		} catch (XMLStreamException e) {
			throw new IOException(e);
		}
		return is == null ? null : new InputSource(is);
	}

	private InputStream getInputStream(String string) throws IOException {
		URL url = Platform.getBundle("org.taobao.ibatiside.model").getEntry(
				"model/" + string);
		return url.openStream();
	}

	@Override
	public Object resolveEntity(String publicId, String systemId,
			String baseURI, String namespace) throws XMLStreamException {
		try {
			if (ArrayUtils
					.indexOf(IbatisConstant.V2_CONFIG_PUBLIC_ID, publicId) != ArrayUtils.INDEX_NOT_FOUND
					&& ArrayUtils.indexOf(IbatisConstant.V2_CONFIG_SYSTEM_ID,
							systemId) != ArrayUtils.INDEX_NOT_FOUND) {
				return getInputStream("config2.dtd");
			} else if (ArrayUtils.indexOf(IbatisConstant.V2_MAP_PUBLIC_ID,
					publicId) != ArrayUtils.INDEX_NOT_FOUND
					&& ArrayUtils.indexOf(IbatisConstant.V2_MAP_SYSTEM_ID,
							systemId) != ArrayUtils.INDEX_NOT_FOUND) {
				return getInputStream("map2.dtd");
			} else if (ArrayUtils.indexOf(IbatisConstant.V3_CONFIG_PUBLIC_ID,
					publicId) != ArrayUtils.INDEX_NOT_FOUND
					&& ArrayUtils.indexOf(IbatisConstant.V3_CONFIG_SYSTEM_ID,
							systemId) != ArrayUtils.INDEX_NOT_FOUND) {
				return getInputStream("config3.dtd");
			} else if (ArrayUtils.indexOf(IbatisConstant.V3_MAP_PUBLIC_ID,
					publicId) != ArrayUtils.INDEX_NOT_FOUND
					&& ArrayUtils.indexOf(IbatisConstant.V3_MAP_SYSTEM_ID,
							systemId) != ArrayUtils.INDEX_NOT_FOUND) {
				return getInputStream("map3.dtd");
			}
		} catch (Exception e) {
			throw new XMLStreamException(e);
		}
		return null;
	}

}
